package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.BCrypt;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

@Transactional
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {


    @Override
    public ResponseResult login(AdUserDto dto) {
        //1.判断参数是否为空
        if(dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //2.判断是否同时输入用户名和密码
        if(StringUtils.isBlank(dto.getName()) ||  StringUtils.isBlank(dto.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE, "用户名或密码为空");
        }

        //3.根据用户名查询用户
        //LambdaQueryWrapper<AdUser> lambdaQueryWrapper = new LambdaQueryWrapper();
        //lambdaQueryWrapper.eq(AdUser::getName, dto.getName());

        AdUser adUser = getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, dto.getName()));

        //4.判断用户是否存在
        if(adUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "用户不存在");
        }

        //5.取出用户的密文密码
        String pwdDB = adUser.getPassword();

        //6.将用户输入的明文密码与用户在表中的密文密码进行比对
        String pwdLogin = dto.getPassword();
        if(BCrypt.checkpw(pwdLogin,pwdDB)){//7.如果比对成功就登录成功生成token
            String token = AppJwtUtil.getToken(adUser.getId().longValue());
            Map result = new HashMap<>();
            result.put("token", token);

            adUser.setPassword("");
            result.put("user", adUser);

            return ResponseResult.okResult(result);
        } else {
            //8.否则就登录失败
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }

    }
}
